package com.xhwl.centiotdata.suppliersystem.eesd.kede;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xhwl.centiotdata.pojo.constant.KeDeConstant;
import com.xhwl.centiotdata.service.cent.IDeviceCentService;
import com.xhwl.common.dto.cent.device.DeviceDTO;
import com.xhwl.common.dto.cent.eesd.RechargeRecordDTO;
import com.xhwl.common.dto.cent.energy.EesdElectricDetailDTO;
import com.xhwl.common.enums.SubSystemEnum;
import com.xhwl.common.enums.device.DeviceTypeEnum;
import com.xhwl.common.pojo.ResultJson;
import com.xhwl.common.pojo.cent.device.DeviceProjSupplierCategory;
import com.xhwl.common.pojo.cent.eesd.EnergyBillingDetailEntity;
import com.xhwl.common.query.cent.device.DevicePageQuery;
import com.xhwl.common.utils.LocalDateTimeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * @author tangwei
 * @description 科德水电系统
 * @create 2023-05-04 10:37
 */
@Slf4j
@RestController
public class KeDeApiHandler {

    @Autowired
    private KeDeUtil keDeUtil;

    @Autowired
    IDeviceCentService deviceCentService;

    public List<EesdElectricDetailDTO> pullRecord(DeviceProjSupplierCategory config) {
        if (Objects.isNull(config.getProjectId()) || Objects.isNull(config.getProperties())) {
            log.warn("获取科德子系统配置异常,{}", config);
            return new ArrayList<>();
        }
        // 查询设备中台全量的仪表台设备
        DevicePageQuery deviceQuery = new DevicePageQuery();
        deviceQuery.setProjectId(config.getProjectId());
        deviceQuery.setProductId(Integer.valueOf(SubSystemEnum.ENERGY.getId()));
        List<DeviceDTO> listDevice = deviceCentService.listDevice(null, deviceQuery);
        if (CollectionUtils.isEmpty(listDevice)) {
            log.info("平台未配置相关电表信息");
            return new ArrayList<>();
        }
        log.info("获取的仪表台账数为=>{},开始同步科德水电表累计量读数", listDevice.size());
        // 调用科德接口获取水电表累积量
        String url = config.getProperties().getString("url");
        List<EesdElectricDetailDTO> list = new ArrayList<>(listDevice.size());
        listDevice.forEach(obj -> {
            // 封装业务对象
            EesdElectricDetailDTO dto = new EesdElectricDetailDTO();
            dto.setProjectId(config.getProjectId());
            dto.setDeviceId(obj.getNodeId());
            dto.setRate(0.0);
            dto.setTime(new Date());
            dto.setJsonFieldFlag(false);
            String deviceNo = obj.getNodeId();
            if (Objects.equals(obj.getDeviceTypeId(), DeviceTypeEnum.WATT_HOUR_METER.getCode())) {
                dto.setDeviceType(DeviceTypeEnum.WATT_HOUR_METER.getCode());
                // 获取电表id
                Map<String, Object> params = new HashMap<>();
                params.put("elemeterCode", deviceNo);
//                log.info("获取电表读数请求参数数据：{}", JSON.toJSONString(params));
                ResultJson resultJson1 = keDeUtil.getWithAuth(config, params, url + KeDeConstant.USER_ELE_AREA);
                if (Objects.equals(resultJson1.getState(), Boolean.FALSE)) {
                    log.error("电表读数失败,查询电表id失败, 电表编号=>{}", deviceNo);
                    return;
                }
                JSONObject eleInfo = JSONObject.parseObject(resultJson1.getResult().toString());
//                log.info("获取电表读数响应数据：{}", JSON.toJSONString(resultJson1));
                JSONArray eleRows = eleInfo.getJSONArray("rows");
                if (eleRows.isEmpty()) {
                    log.error("电表读数失败,查询电表id为空, 电表编号=>{}", deviceNo);
                    return;
                }
                JSONObject waterMeterResult = (JSONObject) eleRows.get(0);
                String eleMeterId = waterMeterResult.getString("elemeterId");

                // 根据电表id获取电表使用累计量
                Map<String, Object> params2 = new HashMap<>();
                params2.put("elemeterId", eleMeterId);
//                log.info("获取电表累计使用量 请求参数：{}", JSONObject.toJSONString(params2));
                ResultJson resultJson2 = keDeUtil.postWithAuth(config, params2, url + KeDeConstant.ELE_READ_INFO);
                JSONObject readInfo = JSONObject.parseObject(JSON.toJSONString(resultJson2.getResult()));
                if (Objects.equals(resultJson2.getState(), Boolean.FALSE)) {
                    log.info("电表读数失败,获取电表累计量失败=>{}, 电表表号=>{}", readInfo, deviceNo);
                    return;
                }
//                log.info("获取电表累计使用量响应数据：{}", JSON.toJSONString(resultJson2));
                JSONArray errorArray = readInfo.getJSONArray("readError");
                JSONArray recordArray = readInfo.getJSONArray("readSuccess");
                if (recordArray.isEmpty() && !errorArray.isEmpty()) {
                    log.error("电表通讯异常，读数失败，电表编号==>{}", deviceNo);
                    return;
                }
                log.info("获取的电表抄表记录==>{}", recordArray);
                JSONObject amount = (JSONObject) recordArray.get(0);
                EesdElectricDetailDTO.ValueEntity valueEntity = new EesdElectricDetailDTO.ValueEntity();
                valueEntity.setValue(Double.parseDouble(amount.getString("elelastdataLjl")));
                dto.setValue(valueEntity);
                list.add(dto);
            } else if (Objects.equals(obj.getDeviceTypeId(), DeviceTypeEnum.WATER_METER.getCode())) {
                dto.setDeviceType(DeviceTypeEnum.WATER_METER.getCode());
                // 获取水表id
                Map<String, Object> params = new HashMap<>();
                // 根据水表编号查询水表id
                params.put("watermeterCode", deviceNo);
                ResultJson waterResultJson = keDeUtil.getWithAuth(config, params, url + KeDeConstant.USER_WATER_AREA);
                if (Objects.equals(waterResultJson.getState(), Boolean.FALSE)) {
                    log.error("查询水表id失败,水表编号==>{}", deviceNo);
                    return;
                }
                JSONObject waterInfo = JSONObject.parseObject(waterResultJson.getResult().toString());
                JSONArray waterRows = waterInfo.getJSONArray("rows");
                if (waterRows.isEmpty()) {
                    log.error("查询水表id失败,水表编号==>{}", deviceNo);
                    return;
                }
                JSONObject waterMeterResult = (JSONObject) waterRows.get(0);
                String waterMeterId = waterMeterResult.getString("watermeterId");

                // 获取水表累计量
                params.clear();
                params.put("watermeterId", waterMeterId);
                ResultJson resultJson = keDeUtil.postWithAuth(config, params, url + KeDeConstant.READ_WATER_METER);
                if (Objects.equals(resultJson.getState(), Boolean.FALSE)) {
                    log.error("查询水表累计量失败, 水表编号==>{}", deviceNo);
                    return;
                }
                JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(resultJson.getResult()));
                JSONArray recordArray = jsonObject.getJSONArray("rows");
                if (recordArray.isEmpty()) {
                    log.info("获取的水表抄表记录为空，水表编号==>{}, 响应结果==>{}", deviceNo, jsonObject);
                    return;
                }
                recordArray.sort(Comparator.comparing(record -> ((JSONObject) record).getDate("addTime")).reversed());
                JSONObject amount = (JSONObject) recordArray.get(0);
                EesdElectricDetailDTO.ValueEntity valueEntity = new EesdElectricDetailDTO.ValueEntity();
                valueEntity.setValue(Double.parseDouble(amount.getString("waterdataLjl")));
                dto.setValue(valueEntity);
                list.add(dto);
            }
        });
        return list;
    }

    public List<EnergyBillingDetailEntity> pullKeDeElectricityData(DeviceProjSupplierCategory config, Integer intervalDay, String deviceNo) {
        // 根据电表编号查询电表id
        String url = config.getProperties().getString("url");
        Map<String, Object> params = new HashMap<>();
        params.put("elemeterCode", deviceNo);
        ResultJson eleInfo = keDeUtil.getWithAuth(config, params, url + KeDeConstant.USER_ELE_AREA);
        if (Objects.equals(eleInfo.getState(), Boolean.FALSE)) {
            log.error("查询电表id失败, 电表编号=>{}", deviceNo);
            return new ArrayList<>();
        }
        JSONObject eleInfoJson = JSONObject.parseObject(eleInfo.getResult().toString());
        JSONArray eleInfoJsonJSONArray = eleInfoJson.getJSONArray("rows");
        if (eleInfoJsonJSONArray.isEmpty()) {
            log.error("查询电表id为空, 电表编号=>{}", deviceNo);
            return new ArrayList<>();
        }
        JSONObject eleMeterResult = (JSONObject) eleInfoJsonJSONArray.get(0);
        String eleMeterId = eleMeterResult.getString("elemeterId");
        log.info("查询电表id=>{}", eleMeterId);

        // 封装查询电表充值记录参数
        params.clear();
        params.put("elemeterId", eleMeterId);
        params.put("selIssuccess", KeDeConstant.WRITE_SUCCESS);
        handlePullDate(params, intervalDay);
        log.info("电表=>{},查询时间段{}<=>{}", deviceNo, params.get("beginTime"), params.get("endTime"));
        ResultJson resultJson = keDeUtil.postWithAuth(config, params, url + KeDeConstant.ELE_AREA_RECORD);
        if (Objects.equals(resultJson.isState(), Boolean.FALSE)) {
            log.error("查询电表记录失败==>{}", params);
            return new ArrayList<>();
        }
        JSONObject eleRechargeRecord = JSONObject.parseObject(JSON.toJSONString(resultJson.getResult()));
        log.info("电表充值记录==>{}", eleRechargeRecord);
        JSONArray rows = eleRechargeRecord.getJSONArray("rows");
        if (rows.isEmpty()) {
            // 无充值记录，查询用户充值电表状态接口获取余额
            return listDefaultEleData(eleMeterId, url, deviceNo, config);
        }
        return handleJsonData(rows, config, KeDeConstant.ELE_METER);
    }

    public List<EnergyBillingDetailEntity> listDefaultEleData(String eleMeterId, String url, String deviceNo, DeviceProjSupplierCategory config) {
        Map<String, Object> params1 = new HashMap<>();
        params1.put("elemeterId", eleMeterId);
        log.info("档案电表编号==>{}, 查询电表id==>{}", deviceNo, eleMeterId);
        ResultJson resultJson1 = keDeUtil.postWithAuth(config, params1, url + KeDeConstant.ELE_READ_INFO);
        if (Objects.equals(resultJson1.getState(), Boolean.FALSE)) {
            log.error("查询电表档案信息失败==>{}", eleMeterId);
            return new ArrayList<>();
        }
        JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(resultJson1.getResult()));
        JSONArray recordArray = jsonObject.getJSONArray("readSuccess");
        if (recordArray.isEmpty()) {
            log.error("查询电表档案信息为空==>{}", jsonObject);
            return new ArrayList<>();
        }
        // 查询电表单价，计算剩余电量
        String price = null;
        ResultJson resultJson2 = keDeUtil.postWithAuth(config, params1, url + KeDeConstant.ELE_INFO_DETAIL);
        if (Objects.equals(resultJson2.getState(), Boolean.TRUE)) {
            JSONObject jsonObject2 = JSONObject.parseObject(JSON.toJSONString(resultJson2.getResult()));
            price = jsonObject2.getJSONObject("data").getString("priceTotal");
        }
        JSONObject jsonInfo = (JSONObject) recordArray.get(0);
        EnergyBillingDetailEntity entity = new EnergyBillingDetailEntity();
        entity.setProjectId(config.getProjectId());
        entity.setDeviceType(KeDeConstant.ELE_METER);
        entity.setDeviceNo(deviceNo);
        entity.setBalance(new BigDecimal(jsonInfo.getString("elelastdataSyl")));
        entity.setAccumulativeConsumption(new BigDecimal(jsonInfo.getString("elelastdataLjl")));
        entity.setRechargeAmount(BigDecimal.ZERO);
        entity.setTime(LocalDateTime.parse(LocalDateTimeUtils.getNowStr(), DateTimeFormatter.ofPattern(LocalDateTimeUtils.DATE_TIME)));
        if (Objects.nonNull(price) && Objects.nonNull(entity.getBalance())) {
            BigDecimal priceDecimal = new BigDecimal(price);
            entity.setRemaining(entity.getBalance().divide(priceDecimal, 2, RoundingMode.HALF_UP));
        }
        return Collections.singletonList(entity);
    }

    public List<EnergyBillingDetailEntity> pullKeDeWaterData(DeviceProjSupplierCategory config, Integer intervalDay, String deviceNo) {
        // 根据水表编号查询水表id
        String url = config.getProperties().getString("url");
        Map<String, Object> params = new HashMap<>();
        params.put("watermeterCode", deviceNo);
        ResultJson waterInfo = keDeUtil.getWithAuth(config, params, url + KeDeConstant.USER_WATER_AREA);
        if (Objects.equals(waterInfo.getState(), Boolean.FALSE)) {
            log.error("查询水表id失败, 水表编号=>{}", deviceNo);
            return new ArrayList<>();
        }
        JSONObject waterInfoJson = JSONObject.parseObject(waterInfo.getResult().toString());
        JSONArray waterInfoJsonJSONArray = waterInfoJson.getJSONArray("rows");
        if (waterInfoJsonJSONArray.isEmpty()) {
            log.error("查询水表id信息为空, 水表编号=>{}", deviceNo);
            return new ArrayList<>();
        }
        JSONObject waterMeterResult = (JSONObject) waterInfoJsonJSONArray.get(0);
        String waterMeterId = waterMeterResult.getString("watermeterId");

        // 封装查询水表充值记录参数
        params.clear();
        params.put("watermeterId", waterMeterId);
        params.put("selIssuccess", KeDeConstant.WRITE_SUCCESS);
        handlePullDate(params, intervalDay);
        log.info("水表=>{},记录查询时间段{}<=>{}", deviceNo, params.get("beginTime"), params.get("endTime"));
        ResultJson jsonObject = keDeUtil.postWithAuth(config, params, url + KeDeConstant.WATER_AREA_RECORD);
        if (Objects.equals(jsonObject.getState(), Boolean.FALSE)) {
            log.error("查询水表记录失败==>{}", params);
            return new ArrayList<>();
        }
        JSONObject waterRechargeRecord = JSONObject.parseObject(JSON.toJSONString(jsonObject.getResult()));
        log.info("水表充值记录==>{}", waterRechargeRecord);
        JSONArray rows = waterRechargeRecord.getJSONArray("rows");
        if (rows.isEmpty()) {
            // 无充值记录，查询用户档案详情接口
            return listDefaultWaterData(waterMeterId, url, deviceNo, config);
        }
        return handleJsonData(rows, config, KeDeConstant.WATER_METER);
    }

    public List<EnergyBillingDetailEntity> listDefaultWaterData(String waterMeterId, String url, String deviceNo, DeviceProjSupplierCategory config) {
        EnergyBillingDetailEntity entity = new EnergyBillingDetailEntity();
        entity.setDeviceNo(deviceNo);
        entity.setBalance(BigDecimal.ZERO);
        entity.setProjectId(config.getProjectId());
        entity.setDeviceType(KeDeConstant.WATER_METER);
        entity.setRechargeAmount(BigDecimal.ZERO);
        entity.setTime(LocalDateTime.parse(LocalDateTimeUtils.getNowStr(), DateTimeFormatter.ofPattern(LocalDateTimeUtils.DATE_TIME)));

        // 获取水表的余额和使用累计量
        Map<String, Object> params = new HashMap<>();
        params.put("watermeterId", waterMeterId);
        log.info("档案水表编号==>{}, 查询水表id==>{}", deviceNo, waterMeterId);
        ResultJson balanceJson = keDeUtil.postWithAuth(config, params, url + KeDeConstant.WATER_INFO_DETAIL);
        if (Objects.equals(balanceJson.getState(), Boolean.TRUE)) {
            JSONObject walterBalanceJson = JSONObject.parseObject(JSON.toJSONString(balanceJson.getResult()));
            log.info("水表档案详情返回==>{}", walterBalanceJson);
            String balance = walterBalanceJson.getJSONObject("data").getString("userBalance");
            String price = walterBalanceJson.getJSONObject("data").getString("priceTotal");
            log.info("水表编号==>{},获取余额==>{}, 水表单价==>{}", deviceNo, balance, price);
            if (StringUtils.isNotBlank(balance) && StringUtils.isNotBlank(price)) {
                BigDecimal priceDecimal = new BigDecimal(price);
                BigDecimal balanceDecimal = new BigDecimal(balance);
                entity.setBalance(balanceDecimal);
                entity.setRemaining(balanceDecimal.divide(priceDecimal, 2, RoundingMode.HALF_UP));
            }
        }
        ResultJson amountJson = keDeUtil.postWithAuth(config, params, url + KeDeConstant.READ_WATER_METER);
        if (Objects.equals(amountJson.getState(), Boolean.TRUE)) {
            // 计算累积量
            JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(amountJson.getResult()));
            JSONArray recordArray = jsonObject.getJSONArray("rows");
            if (!recordArray.isEmpty()) {
                recordArray.sort(Comparator.comparing(obj -> ((JSONObject) obj).getDate("addTime")).reversed());
                JSONObject jsonObject1 = (JSONObject) recordArray.get(0);
                BigDecimal decimal = new BigDecimal(jsonObject1.getString("waterdataLjl"));
                entity.setAccumulativeConsumption(decimal);
            }
        }
        return Collections.singletonList(entity);
    }

    private void handlePullDate(Map<String, Object> params, Integer intervalDay) {
        if (Objects.isNull(intervalDay)) {
            params.put("beginTime", LocalDateTimeUtils.getYearMonthDay());
            params.put("endTime", LocalDateTimeUtils.getYearMonthDay());
        } else {
            // 处理提前interval天的数据
            LocalDate localDate = LocalDate.now().minusDays(intervalDay);
            String ymd = localDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            params.put("beginTime", ymd);
            params.put("endTime", ymd);
        }
    }

    private List<EnergyBillingDetailEntity> handleJsonData(JSONArray rows, DeviceProjSupplierCategory config, Integer deviceType) {
        Integer projectId = config.getProjectId();
        List<EnergyBillingDetailEntity> list = new ArrayList<>(rows.size());
        // 处理数据
        rows.forEach(item -> {
            JSONObject jb = (JSONObject) item;
            EnergyBillingDetailEntity entity = new EnergyBillingDetailEntity();
            entity.setProjectId(projectId);
            entity.setDeviceType(deviceType);
            String deviceNo = Objects.equals(deviceType, KeDeConstant.WATER_METER) ? jb.getString("watermeterCode") : jb.getString("elemeterCode");
            entity.setDeviceNo(deviceNo);
            // 水/电的单价
            BigDecimal priceDecimal = new BigDecimal(jb.getString("price"));
            // 充值时间
            LocalDateTime ldt = LocalDateTime.parse(jb.getString("dtime"), DateTimeFormatter.ofPattern(LocalDateTimeUtils.DATE_TIME));
            entity.setTime(ldt);
            // 充值金额
            String payMoney = jb.getString("smoney");
            if (StringUtils.isNotBlank(payMoney)) {
                entity.setRechargeAmount(new BigDecimal(payMoney));
            }
            // 余水量/余电量 = 充值后金额 / 单价
            BigDecimal eeleDecimal = new BigDecimal(jb.getString("eele"));
            entity.setRemaining(eeleDecimal.divide(priceDecimal, 2, RoundingMode.HALF_UP));
            // 水/电费余额 = 充值后金额
            entity.setBalance(eeleDecimal);
            list.add(entity);
        });
        return list;
    }

    public BigDecimal getWaterOrElectricityReadInfo(DeviceProjSupplierCategory supplierCategory, EnergyBillingDetailEntity entity) {
        JSONObject amount;
        ResultJson resultJson;
        JSONObject jsonObject;
        Map<String, Object> params = new HashMap<>();
        String url = supplierCategory.getProperties().getString("url");
        if (KeDeConstant.WATER_METER.equals(entity.getDeviceType())) {
            // 根据水表编号查询水表id
            params.put("watermeterCode", entity.getDeviceNo());
            ResultJson waterResultJson = keDeUtil.getWithAuth(supplierCategory, params, url + KeDeConstant.USER_WATER_AREA);
            if (Objects.equals(waterResultJson.getState(), Boolean.FALSE)) {
                log.error("查询电表id失败==>{}", entity.getDeviceNo());
                return null;
            }
            JSONObject waterInfo = JSONObject.parseObject(waterResultJson.getResult().toString());
            JSONArray waterRows = waterInfo.getJSONArray("rows");
            if (waterRows.isEmpty()) {
                log.error("查询水表id为空==>{}", entity.getDeviceNo());
                return null;
            }
            JSONObject waterMeterResult = (JSONObject) waterRows.get(0);
            String waterMeterId = waterMeterResult.getString("watermeterId");
            log.info("查询水表id==>{}", waterMeterId);
            // 根据水表id获取水表累积量
            params.clear();
            params.put("watermeterId", waterMeterId);
            resultJson = keDeUtil.postWithAuth(supplierCategory, params, url + KeDeConstant.READ_WATER_METER);
            if (Objects.equals(resultJson.getState(), Boolean.FALSE)) {
                log.error("查询水表累计量失败==>{}", waterMeterId);
                return null;
            }
            jsonObject = JSONObject.parseObject(JSON.toJSONString(resultJson.getResult()));
            JSONArray recordArray = jsonObject.getJSONArray("rows");
            log.info("获取的水表抄表记录==>{}", recordArray);
            if (recordArray.isEmpty()) {
                return null;
            }
            recordArray.sort(Comparator.comparing(obj -> ((JSONObject) obj).getDate("addTime")).reversed());
            amount = (JSONObject) recordArray.get(0);
            return new BigDecimal(amount.getString("waterdataLjl"));
        } else {
            // 根据电表编号查询电表id
            params.put("elemeterCode", entity.getDeviceNo());
            ResultJson eleResultJson = keDeUtil.getWithAuth(supplierCategory, params, url + KeDeConstant.USER_ELE_AREA);
            if (Objects.equals(eleResultJson.getState(), Boolean.FALSE)) {
                log.error("查询电表id失败==>{}", entity.getDeviceNo());
                return null;
            }
            JSONObject eleInfo = JSONObject.parseObject(eleResultJson.getResult().toString());
            JSONArray eleRows = eleInfo.getJSONArray("rows");
            if (eleRows.isEmpty()) {
                log.error("查询电表id为空==>{}", entity.getDeviceNo());
                return null;
            }
            JSONObject waterMeterResult = (JSONObject) eleRows.get(0);
            String eleMeterId = waterMeterResult.getString("elemeterId");
            log.info("查询电表id==>{}", eleMeterId);
            // 根据电表id获取电表使用累计量
            params.clear();
            params.put("elemeterId", eleMeterId);
            resultJson = keDeUtil.postWithAuth(supplierCategory, params, url + KeDeConstant.ELE_READ_INFO);
            jsonObject = JSONObject.parseObject(JSON.toJSONString(resultJson.getResult()));
            if (Objects.equals(resultJson.getState(), Boolean.FALSE)) {
                log.error("查询电表累计量失败==>{}", eleMeterId);
                return null;
            }
            JSONArray recordArray = jsonObject.getJSONArray("readSuccess");
            log.info("获取的电表抄表记录==>{}", recordArray);
            if (recordArray.isEmpty()) {
                return null;
            }
            amount = (JSONObject) recordArray.get(0);
            return new BigDecimal(amount.getString("elelastdataLjl"));
        }
    }

    public ResultJson rechargeElectricityAndWater(DeviceProjSupplierCategory supplierCategory, RechargeRecordDTO dto) {
        if (Objects.isNull(supplierCategory)) {
            return ResultJson.fail("未配置供应商");
        }
        // 封装参数
        Map<String, Object> params = new HashMap<>();
        params.put("money", dto.getRechargeAmount());
        params.put("adds", KeDeConstant.FORWARD_TYPE);
        params.put("selOrderno", dto.getOrderNo());
        params.put("payType", dto.getPayType());
        String url = supplierCategory.getProperties().getString("url");
        String api;
        String eleMeterId = null;
        Map<String, Object> params2 = new HashMap<>();
        if (Objects.equals(dto.getRechargeType(), KeDeConstant.WATER_METER)) {
            // 根据水表编号获取水表id
            params2.put("watermeterCode", dto.getDeviceNo());
            ResultJson waterInfo = keDeUtil.getWithAuth(supplierCategory, params2, url + KeDeConstant.USER_WATER_AREA);
            if (!waterInfo.isState()) {
                log.error("查询水表id失败,水表编号==>{}", dto.getDeviceNo());
                return ResultJson.fail("充值失败，查询水表信息失败");
            }
            JSONObject waterInfoJson = JSONObject.parseObject(waterInfo.getResult().toString());
            JSONArray waterInfoJsonJSONArray = waterInfoJson.getJSONArray("rows");
            if (waterInfoJsonJSONArray.isEmpty()) {
                log.error("查询水表id信息为空,水表编号==>{}", dto.getDeviceNo());
                return ResultJson.fail("充值失败，查询水表信息失败");
            }
            JSONObject jsonObject = (JSONObject) waterInfoJsonJSONArray.get(0);
            String waterMeterId = jsonObject.getString("watermeterId");
            params.put("watermeterId", waterMeterId);
            api = url + KeDeConstant.WATER_PAY;
        } else {
            // 根据电表编号获取电表id
            params2.put("elemeterCode", dto.getDeviceNo());
            ResultJson eleInfo = keDeUtil.getWithAuth(supplierCategory, params2, url + KeDeConstant.USER_ELE_AREA);
            if (!eleInfo.isState()) {
                log.error("查询电表id失败,电表编号==>{}", dto.getDeviceNo());
                return ResultJson.fail("充值失败，查询电表信息失败");
            }
            JSONObject eleInfoJson = JSONObject.parseObject(eleInfo.getResult().toString());
            JSONArray eleInfoJsonArray = eleInfoJson.getJSONArray("rows");
            if (eleInfoJsonArray.isEmpty()) {
                log.error("查询电表id信息为空，电表编号==>{}", dto.getDeviceNo());
                return ResultJson.fail("充值失败，查询电表信息失败");
            }
            JSONObject jsonObject = (JSONObject) eleInfoJsonArray.get(0);
            eleMeterId = jsonObject.getString("elemeterId");
            params.put("elemeterId", eleMeterId);
            api = url + KeDeConstant.ELECTRICITY_PAY;
            // 判断电表是否通讯正常
            params2.clear();
            params2.put("elemeterId", eleMeterId);
            ResultJson resultJson1 = keDeUtil.postWithAuth(supplierCategory, params2, url + KeDeConstant.ELE_READ_INFO);
            if (Objects.equals(resultJson1.getState(), Boolean.FALSE)) {
                log.error("查询电表档案信息失败==>{}", resultJson1);
                return ResultJson.fail("电表:" + dto.getDeviceNo() + "通讯异常，无法充值");
            }
            JSONObject jsonObject1 = JSONObject.parseObject(JSON.toJSONString(resultJson1.getResult()));
            JSONArray errorArray = jsonObject1.getJSONArray("readError");
            JSONArray successArray = jsonObject1.getJSONArray("readSuccess");
            if (successArray.isEmpty() && !errorArray.isEmpty()) {
                log.error("查询电表档案信息失败==>{}", jsonObject1);
                return ResultJson.fail("电表:" + dto.getDeviceNo() + "通讯异常，无法充值");
            }
        }
        log.info("充值参数==>{},充值类型==>{}", params, dto.getRechargeType());
        ResultJson resultJson = keDeUtil.postWithAuth(supplierCategory, params, api);
        if (resultJson.isState()) {
            /*if (Objects.equals(dto.getRechargeType(), KeDeConstant.ELE_METER)) {
                try {
                    Thread.sleep(30 * 1000);
                } catch (InterruptedException e) {
                    log.error("{}", e.getMessage());
                }
                params.clear();
                params.put("elemeterId", eleMeterId);
                params.put("selOrderno", dto.getOrderNo());
                params.put("beginTime", LocalDateTimeUtils.getYearMonthDay());
                params.put("endTime", LocalDateTimeUtils.getYearMonthDay());
                ResultJson rechargeFirstResult = getRechargeState(supplierCategory, params, url + KeDeConstant.ELE_AREA_RECORD);
                if (!rechargeFirstResult.isState()) {
                    log.error("{}第一次查询写表状态失败==>{}", dto.getDeviceNo(), rechargeFirstResult.getMessage());
                    try {
                        Thread.sleep(90 * 1000);
                    } catch (InterruptedException e) {
                        log.error("{}", e.getMessage());
                    }
                    ResultJson rechargeSecondResult = getRechargeState(supplierCategory, params, url + KeDeConstant.ELE_AREA_RECORD);
                    if (!rechargeSecondResult.isState()) {
                        log.error("{}第二次查询写表状态失败==>{}", dto.getDeviceNo(), rechargeFirstResult.getMessage());
                        try {
                            Thread.sleep(3 * 60 * 1000);
                        } catch (InterruptedException e) {
                            log.error("{}", e.getMessage());
                        }
                        ResultJson rechargeFinalResult = getRechargeState(supplierCategory, params, url + KeDeConstant.ELE_AREA_RECORD);
                        if (!rechargeFinalResult.isState()) {
                            log.error("{}第三次查询写表状态失败==>{}", dto.getDeviceNo(), rechargeFirstResult.getMessage());
                            return rechargeFinalResult;
                        }
                    }
                }
                log.info("{}写表成功，充值成功", dto.getDeviceNo());
            }*/
            return ResultJson.success("科德平台充值成功");
        }
        return ResultJson.fail(resultJson.getMessage());
    }

    private ResultJson getRechargeState(DeviceProjSupplierCategory supplierCategory, Map<String, Object> params, String api) {
        ResultJson judgeJson = keDeUtil.postWithAuth(supplierCategory, params, api);
        if (Objects.equals(judgeJson.isState(), Boolean.FALSE)) {
            log.error("充值后查询电表记录失败==>{}", params);
            return ResultJson.fail("充值失败，查询电表写表记录失败");
        }
        JSONObject eleRechargeRecord = JSONObject.parseObject(JSON.toJSONString(judgeJson.getResult()));
        log.info("电表充值记录{},params{},api{}", eleRechargeRecord, params, api);
        JSONArray rows = eleRechargeRecord.getJSONArray("rows");
        if (rows.isEmpty()) {
            return ResultJson.fail("充值失败，查询电表写表记录失败");
        }
        JSONObject eleJson = (JSONObject) rows.get(0);
        if (!KeDeConstant.WRITE_SUCCESS.equals(eleJson.getInteger("selIssuccess"))) {
            log.info("写表失败==>{}", eleJson);
            return ResultJson.fail("充值失败, 电表写表失败");
        }
        return ResultJson.success("查询写表状态成功");
    }

    public ResultJson controlElectricityMeter(DeviceProjSupplierCategory supplierCategory, String deviceNo, Integer cutoffState) {
        if (Objects.isNull(supplierCategory)) {
            log.error("科德子系统未配置供应商");
        }
        // 获取电表id
        String url = supplierCategory.getProperties().getString("url");
        Map<String, Object> params = new HashMap<>();
        params.put("elemeterCode", deviceNo);
        ResultJson getResultJson = keDeUtil.getWithAuth(supplierCategory, params, url + KeDeConstant.USER_ELE_AREA);
        if (Objects.equals(getResultJson.getState(), Boolean.FALSE)) {
            log.error("查询电表id信息失败，电表编号==>{}", deviceNo);
            return ResultJson.fail("通断闸失败，查询电表id接口失败");
        }
        JSONObject jsonObject = JSONObject.parseObject(getResultJson.getResult().toString());
        JSONArray array = jsonObject.getJSONArray("rows");
        if (array.isEmpty()) {
            log.error("查询电表id信息为空，电表编号==>{}", deviceNo);
            return ResultJson.fail("通断闸失败，查询电表id信息为空");
        }
        JSONObject elemeterInfo = (JSONObject) array.get(0);
        String eleMeterId = elemeterInfo.getString("elemeterId");

        params.clear();
        params.put("elemeterId", eleMeterId);
        params.put("meterplanRoad", KeDeConstant.METER_PLAN_LOAD);
        if (Objects.equals(cutoffState, KeDeConstant.OFF_STATUS)) {
            params.put("onoffType", KeDeConstant.SINGLE_OFF_TYPE);
        } else if (Objects.equals(cutoffState, KeDeConstant.ON_STATUS)) {
            params.put("onoffType", KeDeConstant.SINGLE_ON_TYPE);
        }
        ResultJson resultJson = keDeUtil.postWithAuth(supplierCategory, params, url + KeDeConstant.CONTROL_ELE_ON_OR_OFF);
        if (!resultJson.isState()) {
            log.error("操作科德电表通断闸失败,cutoffState=>{}, resultJson==>{}", cutoffState, resultJson);
        }
        return resultJson;
    }

    public void ownAlarmPush(DeviceProjSupplierCategory supplierCategory, JSONObject jsonParams) {
        String url = supplierCategory.getProperties().getString("url") + KeDeConstant.FENG_ZE_ALARM_PUSH;
        Map<String, Object> params = new HashMap<>();
        params.put("Resultno", UUID.randomUUID().toString().substring(0, 13));
        params.put("contractNo", jsonParams.get("deviceNo"));
        params.put("Currentmargin", jsonParams.get("amount"));
        params.put("Currentamount", jsonParams.get("balance"));
        params.put("rechargeType", jsonParams.get("deviceType"));
        log.info("调用酆泽欠费推送接口入参==>{}", params);
        ResultJson resultJson = keDeUtil.postWithAuth(supplierCategory, params, url);
        if (!resultJson.isState()) {
            log.error("推送消息失败,参数==>{},结果==>{}", JSON.toJSONString(params), resultJson.getMessage());
        }
    }

}
